package 多线程;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author zhang lei
 * @Date 2021-12-24 17:16
 */
public class SychronizedTest {

    private static SychronizedTest inst;

    private static boolean b = true;

    private SychronizedTest() {

    }

    public static SychronizedTest getInst() throws InterruptedException {
        if(inst == null) {
            System.out.println("进入判断1: "+Thread.currentThread().getName());
            synchronized (SychronizedTest.class) {
                System.out.println("进入类锁: "+Thread.currentThread().getName());
                if(inst == null) {
//                    if(b) {
//                        System.out.println("进入flag: "+Thread.currentThread().getName());
//                        b = false;
//                        Thread.sleep(5000);
//                    }
                    inst = new SychronizedTest();
                    System.out.println("进入判断2: "+Thread.currentThread().getName());
                    return inst;
                }
            }
        }
        return inst;
    }

    public static void main(String[] args) {
        ExecutorService e = Executors.newFixedThreadPool(3);
        try {
            for (int i = 0; i < 3; i++) {
                e.execute(() -> {
                    try {
                        System.out.println(SychronizedTest.getInst());
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                });
            }
        } finally {
            e.shutdown();
        }
    }
}
